package com.axc.gallery2.net.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.axc.gallery2.R;
import com.axc.gallery2.camera.activity.CameraResultactivity;
import com.axc.gallery2.net.ApiInvoker;
import com.axc.gallery2.net.AsyncDownPhotos;
import com.axc.gallery2.view.GridViewActivity;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.common.AbstractRequestListener;
import com.renren.api.connect.android.exception.RenrenError;
import com.renren.api.connect.android.photos.PhotoUploadRequestParam;
import com.renren.api.connect.android.photos.PhotoUploadResponseBean;

/**
 * 上传照片的Activity
 * 
 */
public class UploadPhotoActivity extends BaseActivity {
	/**
	 * 标识数据状态的消息值，依次为发送成功，出现异常，出现严重错误
	 */
	private final static int DATA_COMPLETE = 0xffff;
	private final static int DATA_ERROR = 0xfffe;
	private final static int DATA_FAULT = 0xfffd;

	/**
	 * 压缩度
	 */
	int preeValue;
	/**
	 * Bundle参数设置中的字符串标识符
	 */
	private final static String BEAN_LABEL = "bean";
	private final static String ERROR_LABEL = "error";

	/**
	 * 上传的文件对象
	 */
	File file;
	/**
	 * 相册描述
	 */
	EditText photoCaptionValue;
	/**
	 * 相册缩略图
	 */
	ImageView photoViewImage;
	/**
	 * 上传按钮
	 */
	Button uploadButton;
	/**
	 * 显示调用返回结果的EditText
	 */
	EditText showResult;
	/**
	 * 选择模式列表
	 */
	ListView listView;
	/**
	 * 上传模式对话框
	 */
	AlertDialog uploadAlertDialog;
	/**
	 * 自定义上传模式对话框
	 */
	AlertDialog customUploadAlertDialog;
	/**
	 * 调用上传API的参数
	 */
	PhotoUploadRequestParam photoParam = new PhotoUploadRequestParam();
	// private String path;

	// 主题应用
	public static UploadPhotoActivity Talbum;
	public int theme = -1;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 主题
		Talbum = this;
		theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
				android.R.style.Theme);
		setTheme(theme);
		super.onCreate(savedInstanceState);
		listView = new ListView(this);
		DListAdapter adapter = new DListAdapter(this);
		adapter.getList().clear();
		List<String> list = new ArrayList<String>();
		list.add("无压缩");
		list.add("精细压缩");
		list.add("普通压缩");
		list.add("高度压缩");
		list.add("自定义");
		uploadAlertDialog =new AlertDialog.Builder(this).setTitle(
				"选择模式").setView(listView).create();
		final SeekBar seekBar =new SeekBar(this);
		seekBar.setMax(100);
		seekBar.setProgress(50);
		seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener );
		customUploadAlertDialog =new AlertDialog.Builder(this).setView(seekBar).setTitle("图片质量")
				.setPositiveButton(R.string.sure, new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						UploadPhoto(seekBar.getProgress());				
					}
				}).create();
		adapter.setList(list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(onItemClickListener);

		// 设置布局
		setContentView(R.layout.photo_upload_layout);
		// 获取上传图片路径
		// path = this.getIntent().getExtras().getString(ImageInfo.IAMGEPATH);
		// 获取intent中的renren和file对象
		Object object =getIntent().getSerializableExtra("file");
		
		// 使用BaseActivity的renren对象
		if(object==null){
			if(dialog==null){
				dialog=new Dialog(this, R.style.dialog_style);
				LayoutInflater iLayoutInflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View view=iLayoutInflater.inflate(R.layout.edit_dialog, null);
				View.OnClickListener onClickListener =new View.OnClickListener() {


					@Override
					public void onClick(View v) {
						//设置动画
						ScaleAnimation animation=new ScaleAnimation(0.8f, 1.1f, 0.8f, 1.1f, 80,80);
						AlphaAnimation animation2 =new AlphaAnimation(0.5f, 1);
						animation2.setDuration(1000);
						animation.setDuration(1000);
						AnimationSet animationSet; animationSet=new AnimationSet(true);
						animationSet.addAnimation(animation);
						animationSet.addAnimation(animation2);
						animationSet.setDuration(1000);
						v.setAnimation(animationSet);
						switch (v.getId()) {
						//拍照
						case R.id.index_c:
							startActivity(new Intent(getBaseContext(),CameraResultactivity.class));
							break;						
							//图库选择
						case R.id.index_e:
							Intent intent  = new Intent();
							intent.setClass(getBaseContext(), GridViewActivity.class);					
							startActivity(intent);
							finish();
							break;

						default:
							break;
						}
						dialog.dismiss();
						return;
					}

				};



				View index_e = view.findViewById(R.id.index_e);
				index_e.setOnClickListener(onClickListener);


				View index_c = view.findViewById(R.id.index_c);
				index_c.setOnClickListener(onClickListener);



				dialog.setContentView(view);
			}
			dialog.show();
			return;
		}
		//获取上传对象
		file = (File)object ;
		// 初始化人人网络相册
		renren = new Renren(NetAlbumsActivity.getApiKey(), NetAlbumsActivity
				.getSecretKey(), NetAlbumsActivity.getAppId(), this);
		ApiInvoker.init(renren);

		if (renren == null) {
			showTip("renren对象为空，无法上传照片！");
		}
		//没有通过验证
		else if(!renren.isAccessTokenValid()) {
			new AlertDialog.Builder(this).setTitle(R.string.dialogtitle).setMessage(R.string.gridview_dialog_nologin).setNegativeButton(R.string.cancel, null)
			.setPositiveButton(R.string.gridview_dialog_login, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent =new Intent(UploadPhotoActivity.this,NetAlbumsActivity.class);
					UploadPhotoActivity.this.startActivity(intent);
				}
			}).create().show();
		}
		photoCaptionValue = (EditText) findViewById(R.id.renren_photo_caption);

		photoViewImage = (ImageView) findViewById(R.id.renren_photo_image);
		// 设置缩略图
		Bitmap bitmap = null;
		// bitmap = BitmapFactory.decodeFile(path);
		try {
			bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			showTip("设置缩略图出现异常");
		}
		photoViewImage.setImageBitmap(bitmap);

		uploadButton = (Button) findViewById(R.id.renren_photo_upload_button);

		uploadButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				uploadAlertDialog.show();	

			}
		});
	}
	/**
	 * 上传图片
	 */
	private void UploadPhoto(int value) {
		// 设置caption参数
		String caption = photoCaptionValue.getText().toString();
		if (caption != null && !"".equals(caption.trim())) {
			photoParam.setCaption(caption);
		}
		// 设置file参数
		photoParam.setFile(file);
		// 调用SDK异步上传照片的接口
		new AsyncDownPhotos(renren, getBaseContext()).publishPhoto(
				photoParam,
				new AbstractRequestListener<PhotoUploadResponseBean>() {
					@Override
					public void onRenrenError(RenrenError renrenError) {
						if (renrenError != null) {
							Message message = new Message();
							Bundle bundle = new Bundle();
							bundle.putString(ERROR_LABEL, renrenError
									.getMessage());
							message.what = DATA_ERROR;
							message.setData(bundle);
							handler.sendMessage(message);
						}
					}

					@Override
					public void onFault(Throwable fault) {
						if (fault != null) {
							Message message = new Message();
							Bundle bundle = new Bundle();
							bundle.putString(ERROR_LABEL, fault
									.getMessage());
							message.what = DATA_FAULT;
							message.setData(bundle);
							handler.sendMessage(message);
						}
					}

					@Override
					public void onComplete(PhotoUploadResponseBean bean) {
						if (bean != null) {
							Message message = new Message();
							Bundle bundle = new Bundle();
							bundle.putParcelable(BEAN_LABEL, bean);
							message.what = DATA_COMPLETE;
							message.setData(bundle);
							handler.sendMessage(message);
						}
					}
				});

		// 正在上传照片，显示进度框
		showProgress("正在上传照片", "Wating...");
	}
	//滑动值选择
	OnSeekBarChangeListener onSeekBarChangeListener =new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStartTrackingTouch(SeekBar arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProgressChanged(SeekBar sBar, int progress, boolean arg2) {
			sBar.setProgress(progress);			
		}
	};
	/**
	 * 列表选择事件
	 */
	OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			switch (position) {
			case 0:// 无压缩
				UploadPhoto(0);
				break;
			case 1:// 精细压缩
				UploadPhoto(10);
				break;
			case 2:// 普通压缩
				UploadPhoto(30);
				break;
			case 3:// 默认压缩
				UploadPhoto(-1);
				break;
			case 4:// 自定义
				customUploadAlertDialog.show();
				break;
			default:// 默认压缩
				UploadPhoto(-1);
				break;
			}
			uploadAlertDialog.dismiss();

		}

	};

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			// 显示结果的EditText
			showResult = (EditText) findViewById(R.id.renren_photo_upload_result);
			Bundle bundle = null;

			switch (msg.what) {
			case DATA_COMPLETE:
				// 照片上传成功，结束进度框
				dismissProgress();
				// 显示结果
				bundle = msg.getData();
				if (bundle != null) {
					PhotoUploadResponseBean bean = bundle
							.getParcelable(BEAN_LABEL);

					if (bean != null) {
						showResult.setText("上传图片成功");
					}
				}
				bundle = null;

				break;
			case DATA_ERROR:
				dismissProgress();
				// 显示错误信息
				bundle = msg.getData();
				if (bundle != null) {
					String errorMessage = bundle.getString(ERROR_LABEL);

					if (errorMessage != null) {
						showResult.setText(errorMessage);
					}
				}
				bundle = null;

				break;
			case DATA_FAULT:
				dismissProgress();
				// 显示错误信息
				bundle = msg.getData();
				if (bundle != null) {
					String errorMessage = bundle.getString(ERROR_LABEL);

					if (errorMessage != null) {
						showResult.setText(errorMessage);
					}
				}
				bundle = null;

				break;
			default:
				dismissProgress();
				break;
			}
		}

	};

	@Override
	protected void LoadOut() {
		try {
			renren.logout(UploadPhotoActivity.this);
			Intent intent = new Intent();
			intent.setClass(UploadPhotoActivity.this, NetAlbumsActivity.class);
			UploadPhotoActivity.this.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
